package com.lechuang.songbo.view.activity.get;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.lechuang.songbo.R;
import com.lechuang.songbo.model.ShareModel;
import com.lechuang.songbo.model.bean.GetBean;
import com.lechuang.songbo.model.bean.ShareImageBean;
import com.lechuang.songbo.presenter.net.Netword;
import com.lechuang.songbo.presenter.net.QUrl;
import com.lechuang.songbo.utils.QRCodeUtils;
import com.lechuang.songbo.view.defineView.SpannelTextView;
import com.lechuang.songbo.view.dialog.ShareDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

public class GetShareActivity extends AppCompatActivity {

    private GetBean.ListInfo listInfo;
    private TextView clipText;
    private TextView mSelectTextView;
    private RecyclerView mImageRecyclerView;
    private int mSelectCount = 1;//默认选中第一个
    private List<ShareImageBean> shareImageBeanList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_share);
        shareHandler = new ShareHandler(this);
        listInfo = (GetBean.ListInfo) getIntent().getSerializableExtra("listInfo");
        initView();

        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("itemNumId", String.format(Locale.CHINESE, "%d", listInfo.alipayItemId));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        String url = null;
                        try {
                            url = "https://api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?&api=mtop.taobao.detail.getdetail&v=6.0&ttid=2013@taobao_h5_1.0.0&type=jsonp&dataType=jsonp&data="
                                    + URLEncoder.encode(jsonObject.toString(), "utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }


                        okhttp3.OkHttpClient okHttpClient = Netword.getInstance().getOkHttpClient();
                        Request.Builder builder = new Request.Builder();
                        builder.url(url);
                        Request request = builder.build();
                        final Call call = okHttpClient.newCall(request);
                        try {
                            Response response = call.execute();
                            String result = response.body().string();
                            if (TextUtils.isEmpty(result)) return;
                            JSONObject root = new JSONObject(result);
                            JSONObject dataObject = root.getJSONObject("data");
                            JSONObject itemObject = dataObject.getJSONObject("item");
                            JSONArray imageArray = itemObject.getJSONArray("images");
                            ShareImageBean shareImageBean;
                            for (int x = 0; x < imageArray.length(); x++) {
                                shareImageBean = new ShareImageBean();
                                shareImageBean.setUrl(imageArray.getString(x));
                                shareImageBean.setmSelected(x == 0);
                                shareImageBeanList.add(shareImageBean);
                            }
                            listener.load(shareImageBeanList);

                        } catch (IOException | JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
        ).start();
    }

    private OnShareImageSelectCallback callback = new OnShareImageSelectCallback() {
        @Override
        public void select(boolean flag) {
            if (flag) {
                mSelectCount++;
            } else {
                mSelectCount--;
            }
            mSelectTextView.setText(String.format(Locale.CHINESE, "已选%d张", mSelectCount));
        }
    };


    private interface OnShareImageLoadListener {
        void load(List<ShareImageBean> beanList);
    }

    private interface OnShareImageSelectCallback {
        void select(boolean flag);
    }

    private OnShareImageLoadListener listener = new OnShareImageLoadListener() {
        @Override
        public void load(List<ShareImageBean> beanList) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mImageRecyclerView.setLayoutManager(new LinearLayoutManager(GetShareActivity.this, LinearLayoutManager.HORIZONTAL, false));
                    mImageRecyclerView.addItemDecoration(new DividerItemDecoration(GetShareActivity.this, DividerItemDecoration.HORIZONTAL));
                    final ImageListAdapter imageListAdapter = new ImageListAdapter();
                    imageListAdapter.addData(shareImageBeanList);
                    mImageRecyclerView.setAdapter(imageListAdapter);
                    imageListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                        @Override
                        public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                            ShareImageBean bean = imageListAdapter.getData().get(position);

                            callback.select(!bean.ismSelected());
                            bean.setmSelected(!bean.ismSelected());
                            imageListAdapter.notifyItemChanged(position);
                        }
                    });
                }
            });
        }
    };


    private class ImageListAdapter extends BaseQuickAdapter<ShareImageBean, BaseViewHolder> {

        ImageListAdapter() {
            super(R.layout.share_item);
        }

        @Override
        protected void convert(BaseViewHolder helper, ShareImageBean item) {
            String substring = item.getUrl().substring(item.getUrl().indexOf("//") + 2);
            Glide.with(GetShareActivity.this).load("http://" + substring).into((ImageView) helper.getView(R.id.share_item_iamgeview));
            helper.addOnClickListener(R.id.share_item_select);
            ImageButton mSelectButton = helper.getView(R.id.share_item_select);
            mSelectButton.setSelected(item.ismSelected());
        }
    }


    private void initView() {
        //分享文案
        clipText = (TextView) findViewById(R.id.clipText);
        clipText.setText(listInfo.shareText);
        TextView shareIntegral = (TextView) findViewById(R.id.shareIntegral);
        shareIntegral.setText("代理分享此商品可获" + listInfo.shareIntegral+"积分,普通用户无积分返现");
        findViewById(R.id.iv_back).setVisibility(View.GONE);
        ImageView mTitleBack = (ImageView) findViewById(R.id.iv_black_back);
        mTitleBack.setVisibility(View.VISIBLE);
        mTitleBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ((TextView) findViewById(R.id.tv_black_title)).setText("创建分享");
        mImageRecyclerView = (RecyclerView) findViewById(R.id.image_recyclerView);
        mSelectTextView = (TextView) findViewById(R.id.tv_select_image);
        mSelectTextView.setText(String.format(Locale.CHINESE, "已选%d张", mSelectCount));
    }

    /**
     * 分享
     *
     * @param view
     */
    public void share(View view) {
        //判断是否登陆
//        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
//        boolean isLogin = sp.getBoolean("isLogin", false);
//        if (!isLogin) {
//            startActivityForResult(new Intent(this, LoginActivity.class), 0, null);
//        } else {
//            int isAgency = sp.getInt(LeCommon.KEY_AGENCY_STATUS, 0);
//            if (isAgency == 1) {
//                createBitmap();
//            } else {
//                //TODO 申请代理
//                startActivity(new Intent(this, ApplyAgentActivity.class));
//            }
//        }
        createBitmap();


//        shareByOneShare();
    }

    private String mLocalUrl;
    private View content;

    private void createBitmap() {
        content = getLayoutInflater().inflate(R.layout.bitmap_share, null);
        final ImageView imageView = (ImageView) content.findViewById(R.id.share_image);
        TextView preferentialPrice = (TextView) content.findViewById(R.id.preferentialPrice);
        TextView price = (TextView) content.findViewById(R.id.price);
        final SpannelTextView spannelTextView = (SpannelTextView) content.findViewById(R.id.spannelTextView);
        spannelTextView.setShopType(listInfo.shopType);
        spannelTextView.setDrawText(listInfo.shareText);
        preferentialPrice.setText(listInfo.preferentialPrice + "");
        price.setText(listInfo.price + "");

        Glide.with(this).load(listInfo.img).asBitmap().into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                imageView.setImageBitmap(resource);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        okhttp3.OkHttpClient okHttpClient = Netword.getInstance().getOkHttpClient();
                        Request.Builder builder = new Request.Builder();
                        try {
                            builder.url("https://api.weibo.com/2/short_url/shorten.json?source=1681459862&url_long=" +
                                    URLEncoder.encode(listInfo.tbPrivilegeUrl, "utf-8"));
                            Request request = builder.build();
                            final Call call = okHttpClient.newCall(request);
                            Response response = call.execute();
                            String result = response.body().string();
                            JSONObject jsonObject = new JSONObject(result);
                            JSONArray jsonArray = jsonObject.getJSONArray("urls");
                            JSONObject object = jsonArray.getJSONObject(0);
                            String shortUrl = object.getString("url_short");
                            float scaledDensity = getResources().getDisplayMetrics().scaledDensity;
                            Bitmap qrImage = QRCodeUtils.createQRImage(QUrl.productShare + "?i=" + listInfo.alipayItemId, (int) scaledDensity * 80, (int) scaledDensity * 80);

                            Message message = Message.obtain();
                            message.obj = qrImage;
                            shareHandler.sendMessage(message);
                        } catch (IOException | JSONException e) {
                            e.printStackTrace();
                        }
                    }

                }).start();

            }
        });


    }

    private ShareHandler shareHandler;

    private class ShareHandler extends Handler {
        WeakReference<Context> weakReference;

        public ShareHandler(Context context) {
            weakReference = new WeakReference<>(context);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Context context = weakReference.get();
            if (context == null) return;
            ImageView codeView = (ImageView) content.findViewById(R.id.code);
            codeView.setImageBitmap((Bitmap) msg.obj);
            Bitmap bitmap = saveViewBitmap(content);
            try {
                if (TextUtils.isEmpty(mLocalUrl)) {
                    mLocalUrl = getExternalCacheDir() + "/" + System.currentTimeMillis() + ".png";
                }
                File dir = new File(mLocalUrl);
                FileOutputStream fileOutputStream = new FileOutputStream(dir);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);

                shareByOneShare();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 把View转化为bitmap
     *
     * @param view
     * @return
     */
    private Bitmap saveViewBitmap(View view) {
        view.setDrawingCacheEnabled(true);
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
                , View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(),
                view.getMeasuredHeight());
        view.buildDrawingCache(true);
        Bitmap bitmap = view.getDrawingCache(true);
        if (bitmap == null) {
            bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            view.draw(canvas);
        }
        Bitmap bmp = duplicateBitmap(bitmap);

        view.setDrawingCacheEnabled(false);
        return bmp;

    }

    /**
     * 改变像素点
     *
     * @param bmpSrc
     * @return
     */
    public Bitmap duplicateBitmap(Bitmap bmpSrc) {
        if (null == bmpSrc) {
            return null;
        }
        int bmpSrcWidth = bmpSrc.getWidth();
        int bmpSrcHeight = bmpSrc.getHeight();
        Bitmap bmpDest = Bitmap.createBitmap(bmpSrcWidth, bmpSrcHeight, Bitmap.Config.ARGB_8888);
        if (null != bmpDest) {
            Canvas canvas = new Canvas(bmpDest);
            final Rect rect = new Rect(0, 0, bmpSrcWidth, bmpSrcHeight);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(Color.WHITE);
            canvas.drawRect(rect, paint);
            canvas.drawBitmap(bmpSrc, 0, 0, paint);
        }
        return bmpDest;
    }

    private void shareByOneShare() {
        new ShareModel().gotoShareImage(this, mLocalUrl);
    }


    private ShareDialog shareDialog;

    //剪切板
    public void clip(View view) {
        //剪切板
        ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clipData = ClipData.newPlainText("share", clipText.getText().toString());
        clipboardManager.setPrimaryClip(clipData);
        shareDialog = new ShareDialog(this, listInfo.shareText);
        shareDialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (shareDialog != null) {
            shareDialog.dismiss();
            shareDialog = null;
        }

    }
}
